package com.hbnu.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * 需求：从配置文件获取数据库配置信息
 *
 * @author kittychen
 * @since 2025-10-21 15:44
 */
public class JdbcDemo02 {
    public static void main(String[] args) {
        // 0、获取配置文件中的数据库信息
        // ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
        // String driver = resourceBundle.getString("driver");
        // String url = resourceBundle.getString("url");
        // String username = resourceBundle.getString("username");
        // String password = resourceBundle.getString("password");


        Connection connection = null;
        Statement statement = null;

        try {

            InputStream resourceAsStream = JdbcDemo02.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            String driver = properties.getProperty("driver");
            String url = properties.getProperty("url");
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");

            // 1、注册驱动
            Class.forName(driver);

            // 2、获取连接
            connection = DriverManager.getConnection(url, username, password);

            // 3、获取数据库操作对象
            statement = connection.createStatement();

            // 4、执行SQL语句
            String sql = "insert into tb_user values(3, '李四', '123456', 10000)";
            int rows = statement.executeUpdate(sql);
            System.out.println("受影响的行数：" + rows);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6、释放资源
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
